<?php

/*
+ ---------------------------------------------------------------------- +
| e107Shop - An e-commerce plugin for the e107 content management system |
|                                                                        |
| ByOrder Europe 2007-2009                                               |
| http://e107shop.com                                                    |
| pbielen@gmail.com                                                      |
|                                                                        |
| Released under the terms and conditions of the LGPL                    |
+ ---------------------------------------------------------------------- +
*/

$debugPayment = false;
if (ADMIN && $debugPayment) $checkout = print_a($_REQUEST, true). "<br />";

global $e107shop_db_name, $shop_settings, $cart_id;

// Make data safe
foreach ($_POST as $key => $value) $_POST[$key] = $tp->toDB($value);

//
// Build the display to finalise the payment
//

$checkout .= "<table class='fborder' width='100%'>
            <tr>
                <td class='forumheader' colspan='4'>
                    <b>".lan_payment_preview."</b>
                </td>
            </tr>
            <tr><td colspan='4'><div style='height: 2px;'>&nbsp;</div></td></tr>
            <tr>
                <td class='forumheader' style='text-align: left;'>
                    <strong>".lan_global_product_name."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_quantity."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_price_per_item."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_total."</strong>
                </td>
            </tr>
            <tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";

$sql=new db;
$sql2=new db;
$tblProducts=new db;
$dbrows = 0;

if($sql->db_Select($e107shop_db_name['cart'], "*", "cart_ID='".$cart_id."' order by cart_time")) {
    $price = 0;
    $total_price = 0;
    $customFields = array();
    while($row = $sql -> db_Fetch()){
        $customFields = array($row['field1'], $row['field2'], $row['field3'], $row['field4'], $row['field5'], 
        $row['field6'], $row['field7'], $row['field8'], $row['field9'], $row['field10'], 
        $row['field11'], $row['field12'], $row['field13'], $row['field14'], $row['field15'], 
        $row['field16'], $row['field17'], $row['field18'], $row['field19'], $row['field20']);
        // Calculate the price per item
        $line_product_price = e107shop_get_product_field($row["productID"], "special_price");
        if (floatval($line_product_price) == 0) 
            $line_product_price = e107shop_get_product_field($row["productID"], "product_price");
        // Now check if there are option related tot he product
        $options = explode("|", $row["option"]);
        if(is_array($options)) {
            foreach ($options as $value) {
                $line_option_price = e107shop_get_option_field($value, "optval");
                $line_product_price += $line_option_price;
            }
        }
        $product_total_price = $line_product_price * $row['quantity'];
        $product_price += $line_product_price * $row['quantity'];
        
        // Calculate the postage price
        if($shop_settings["postage_method"] == "3"){
            $quantity += $row['quantity'];
            // always reset the postage price, cause we only want one calculation
            // with the exact amount of quantity
            $postage_price = e107shop_get_postage_price($row["productID"], $quantity, $_POST['customer_region']);
        } else {
            $postage_price += e107shop_get_postage_price($row["productID"], $row['quantity']);
        }
                      
        // Display each item from the cart
        if ($dbrows > 0) {
            $checkout .="<tr><td colspan='4'><hr /></td></tr>";
        }
        $checkout .="<tr><td><div>&nbsp;".e107shop_get_product_field($row["productID"], "product_name")."</div>";
        
        // check if there are product-options before filling the table
        if (is_array($options)) {
            if ($options['0']) $checkout .= "<div style='height: 10px;'>
                                            </div><div>&nbsp;<b>".lan_global_options."</b>";
            foreach ($options as $value) {
                if ($sql2->db_Select($e107shop_db_name['product_options'], "*", "ID='".$value."'")) {
                    while ($row2=$sql2->db_Fetch()) {
                        $checkout .= "<br />&nbsp;".$row2["option_group"].": ".$row2['optname'];
                    }
                }
            }
            if ($options['0']) $checkout .= "</div>";
        }
        // now check if the product is customized by the customer
        $firstRecord = 0;
        if ($customFields[0] != '') {
            // retrieve the names of the custom product fields
            $tblProducts->db_Select($e107shop_db_name['products'], "*", "ID='".$row['productID']."'");
            $tblProductsRow = $tblProducts->db_Fetch();
            $customProductFields = array($tblProductsRow['fname_1'], $tblProductsRow['fname_2'], $tblProductsRow['fname_3'], $tblProductsRow['fname_4'], $tblProductsRow['fname_5'], 
            $tblProductsRow['fname_6'], $tblProductsRow['fname_7'], $tblProductsRow['fname_8'], $tblProductsRow['fname_9'], $tblProductsRow['fname_10'], 
            $tblProductsRow['fname_11'], $tblProductsRow['fname_12'], $tblProductsRow['fname_13'], $tblProductsRow['fname_14'], $tblProductsRow['fname_15'], 
            $tblProductsRow['fname_16'], $tblProductsRow['fname_17'], $tblProductsRow['fname_18'], $tblProductsRow['fname_19'], $tblProductsRow['fname_20']);
            $checkout .= "<div style='height: 10px;'>
            </div>
            <div>&nbsp;<b>".lan_custom_fields."</b>";
            foreach ($customFields as $value) {
                if ($value != '') $checkout .= "<br />&nbsp;".$customProductFields[$firstRecord].": ".$value;
                $firstRecord += 1; 
            }
            $checkout .= "</div>";
        }
        
        $checkout .=    "</td><td><center>".$row["quantity"]."</center></td>";
            
        $checkout .=    "<td style='text-align: right;'>
        ".$shop_settings["currency_symbol"].e107shop_get_numformat($line_product_price)."&nbsp;</td>
        <td style='text-align: right;'>".$shop_settings["currency_symbol"]
        .e107shop_get_numformat($product_total_price)."&nbsp;</td></tr>";
        
        $dbrows++;
    }
}

$tblProducts->db_Close();

if ($shop_settings['tax_inc'] == 1) $product_price = roundfix(e107shop_calculate_excl($product_price, $shop_settings['tax_rate']), 2);

// Set and Check the coupon amount
$coupon_amount = 0;
if($_POST["coupon"]) {
    $coupon_amount = e107shop_apply_coupon($product_price, $_POST["coupon"]);
    $midtotal = $product_price - $coupon_amount;
}

$postage_price = roundfix($postage_price, 2);
$subtotal = roundfix((($product_price - $coupon_amount) + $postage_price), 2);
$tax = roundfix(e107shop_calculate_tax($subtotal, $shop_settings['tax_rate']), 2);
$total = $subtotal + $tax;

// calculation for the payment cost
$paymentId = substr($_POST["payment"], 0, strpos($_POST["payment"], "."));
$extraPaymentInfo = "";
$extraCost = e107shop_calculate_extra_payment($paymentId, $total, $extraPaymentInfo);
$extraCost = roundfix($extraCost, 2);
$grandTotal = roundfix($total + $extraCost, 2);

$checkout .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";
if ($shop_settings['tax_inc'] == 1) {
    $checkout .= "<tr><td colspan='4' class='forumheader' style='text-align: center; font-size: 7pt;'>"
                .lan_global_price_inc."</td></tr>";
} else {
    $checkout .= "<tr><td colspan='4' class='forumheader' style='text-align: center; font-size: 7pt;'>"
                .lan_global_price_exc."</td></tr>";
}
$checkout .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";

$checkout .= "<tr><td colspan='3' style='text-align: right'>".lan_price_exclusive."&nbsp;</td>
<td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($product_price)
."&nbsp;</td></tr>";

if ($coupon_amount > 0) {
    $checkout .= "<tr><td colspan='3' style='text-align: right'>".lan_global_discount."&nbsp;</td>
    <td style='text-align: right'>".$shop_settings["currency_symbol"]."-".e107shop_get_numformat($coupon_amount)
    ."&nbsp;</td></tr>";
    $checkout .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>".lan_global_subtotal."&nbsp;</td>
    <td style='text-align: right; font-weight: bold;'>".$shop_settings["currency_symbol"].e107shop_get_numformat($midtotal)
    ."&nbsp;</td></tr>";
}

$checkout .= "<tr><td colspan='3' style='text-align: right'>".lan_global_postage."&nbsp;</td>
<td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($postage_price)
."&nbsp;</td></tr>";

$checkout .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
.lan_global_subtotal."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
.$shop_settings["currency_symbol"].e107shop_get_numformat($subtotal)."&nbsp;</td></tr>";

$checkout .= "<tr><td colspan='3' style='text-align: right'>".lan_global_tax."&nbsp;</td>
<td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($tax)
."&nbsp;</td></tr>";

$checkout .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
.lan_global_total_price."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
.$shop_settings["currency_symbol"].e107shop_get_numformat($total)."&nbsp;</td></tr>";

if(trim($extraPaymentInfo) != "") { // extra payment of the payment gateway
    $checkout .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
    .constant("lan_gateway_".$paymentId)." Cost (" . $extraPaymentInfo ."): &nbsp;</td><td style='text-align: right; font-weight: bold;''>"
    .$shop_settings["currency_symbol"].e107shop_get_numformat($extraCost)."&nbsp;</td></tr>";
    
    $checkout .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
    .lan_global_total_price."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
    .$shop_settings["currency_symbol"].e107shop_get_numformat($grandTotal)."&nbsp;</td></tr>";
}

$checkout .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";
$checkout .= "<tr><td class='forumheader' colspan='4'>&nbsp;</td></tr>";

$checkout .= "<tr><td colspan='4'><br /><center>";

$checkout .= e107shop_payment_forms($_POST["payment"], $grandTotal, $_POST["customer_name"], $_POST["customer_last_name"], 
$_POST["customer_city"], $_POST["customer_state"], $_POST["customer_country"], $_POST["customer_region"], 
$postage_price, $_POST["customer_zip"], $_POST["customer_address1"] . "<br>" . $_POST["customer_address2"], 
$_POST["customer_email"], $_POST["coupon"]);

$checkout .= "</center><br /></td></tr></table>";

// Add the customer to the database so they dont have to enter their info every time
//
$sql = new db;
if(USER){
    if(!$sql->db_Select($e107shop_db_name['customer_information'], "*", "username='".USERNAME."'")){
        $sql->db_Insert($e107shop_db_name['customer_information'], "0, '".USERNAME."', '".$_POST["customer_name"]."', '".
        $_POST["customer_last_name"]."', '".$_POST["customer_email"]."', '".
        $_POST["customer_address1"]."', '".$_POST["customer_address2"]."', '".
        $_POST["customer_city"]."', '".$_POST["customer_state"]."', '".
        $_POST["customer_country"]."', '".$_POST["customer_region"]."', '".
        $_POST["customer_zip"]."', '".e107shop_order_id()."'");
    } else {
        //
        // Update with the new information first 2 updates are to prevent errors
        //
        if ($_POST["customer_region"]!=""){
            $sql1 = new db;
            $sql1->db_Update($e107shop_db_name['customer_information'], "customer_region='".
            $_POST["customer_region"]."' WHERE username='".USERNAME."'");
        }

        if($_POST["customer_address2"]!=""){
            $sql2= new db;
            $sql2->db_Update($e107shop_db_name['customer_information'], "customer_address2='".
            $_POST["customer_address2"]."' WHERE username='".USERNAME."'");
        }
        $sql3 = new db;
        $sql->db_Update($e107shop_db_name['customer_information'], "customer_name='".$_POST["customer_name"]
        ."', customer_last_name='".$_POST["customer_last_name"]."', customer_email='".$_POST["customer_email"]
        ."',  customer_address1='".$_POST["customer_address1"]."', customer_city='".$_POST["customer_city"]
        ."', customer_state='".$_POST["customer_state"]."', customer_country='".$_POST["customer_country"]
        ."', customer_zip='".$_POST["customer_zip"]."' WHERE username='".USERNAME."'");
    }
} else {
    $sql->db_Insert($e107shop_db_name['customer_information'], "0, 'Guest', '".$_POST["customer_name"]."', '".
    $_POST["customer_last_name"]."', '".$_POST["customer_email"]."', '".$_POST["customer_address1"]."', '".
    $_POST["customer_address2"]."', '".$_POST["customer_city"]."', '".$_POST["customer_state"]."', '".
    $_POST["customer_country"]."', '".$_POST["customer_region"]."', '".$_POST["customer_zip"]."', '".e107shop_order_id()."'", FALSE);
}

//
// TODO: Add routine for storing the order into the databases, otherwise if something goes wrong, 
//       and the user is not linked to the return-page the order and invoice are gone, and the shop-
//       owner has to guess what is ordered, and even worser, he even doesn't know somebody has paid.
//       But only do this with custom payment methods like, paypal, ideal or credit card.
//

if (ADMIN && $debugPayment) {
    $checkout .= "
    <fieldset>
        <legend>Debug Information from within payment.php</legend>
        <b>Product Price:</b> ".$product_price."<br />
        <b>Coupon-amount:</b> ".$coupon_amount."<br />
        <b>Postage Price:</b> ".$postage_price."<br />
        <b>VAT amount:</b> ".$tax."<br />
        <b>Total:</b> ".$total."<br />
        <b>PaymentID:</b> ".$paymentId."<br />
        <b>extraPaymentInfo:</b> ".$extraPaymentInfo."<br />
        <b>Extra Costs:</b> ".$extraCost."<br />
        <b>Grand Total:</b> ".$grandTotal."
    </fieldset>
    ";
}

return $checkout;
